package com.lianniu.web.tea.user.record;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lianniu.web.base.BaseResult;
import com.lianniu.web.tea.product.dao.TeaProductDao;
import com.lianniu.web.tea.product.model.TeaProduct;
import com.lianniu.web.tea.product.service.ITeaProductService;

@Controller
@RequestMapping("/rest/user/product")
public class TeaUserRecordController {
	
	private final static Logger logger = Logger.getLogger(TeaUserRecordController.class);
	
	@Autowired
	private ITeaProductService teaProductService;
	/**
	 * 查询历史记录
	 * @param req
	 * @param res
	 * @return
	 */
	@RequestMapping(value = "/getRecord", method = { RequestMethod.POST, RequestMethod.GET })
	public @ResponseBody BaseResult getRecord(HttpServletRequest req, HttpServletResponse res) {
		List<TeaProduct> teaProductList = new ArrayList<TeaProduct>();
		Cookie[] cookies = req.getCookies();
		if(cookies!=null){
 			for(Cookie c:cookies){
				if(c.getName().equals("historypro"+req.getParameter("userId"))){
					String historypro = c.getValue();
					String[] ids = historypro.split(",");
					//遍历浏览过的商品id
					for(String id:ids){
						//查询数据库，查询对应的商品
						BaseResult baseResult = teaProductService.getTeaProductInfo(Long.valueOf(id));
						//Product product = dao.findById(id);
						//显示到浏览器
						//html += ""+product.getId()+"&nbsp;"+product.getProName()+"&nbsp;"+product.getPrice()+"<br/>";
						teaProductList.add((TeaProduct) baseResult.getData());
					}
				}
			}
		}
		return BaseResult.success(teaProductList);
	}
	/**
	 * 添加历史记录
	 * @param req
	 * @param res
	 * @return
	 */
	@RequestMapping(value = "/addRecord", method = { RequestMethod.POST, RequestMethod.GET })
	public @ResponseBody BaseResult addRecord(HttpServletRequest req, HttpServletResponse res) {
		String id = req.getParameter("productId");
		 /**
         * 创建cookie，并发送
         */
        //1.创建cookie
        Cookie cookie = new Cookie("historypro"+req.getParameter("userId"),createValue(req,id));
        cookie.setMaxAge(60*60*24*30);
        //2.发送cookie
        res.addCookie(cookie);		
        return BaseResult.success("ok");	
	}
	
	/**
	 * 删除历史记录
	 * @param req
	 * @param res
	 * @return
	 */
	@RequestMapping(value = "/deleteRecord", method = { RequestMethod.POST, RequestMethod.GET })
	public @ResponseBody BaseResult deleteRecord(HttpServletRequest req, HttpServletResponse res) {
		Cookie[] cookies = req.getCookies();
		if(cookies!=null){
			for(Cookie cookie:cookies){
				if(cookie.getName().equals("historypro"+req.getParameter("userId"))){
					cookie.setValue(null);  
                    cookie.setMaxAge(0);// 立即销毁cookie  
                    //cookie.setPath("/");  
                    cookie.setDomain("localhost"); 
            		// 设置path 
            		cookie.setPath("/");
                    res.addCookie(cookie);
				}
			}
		}
		return BaseResult.success("ok");	
	}
	
	 public String createValue(HttpServletRequest request,String id){
	        Cookie[] cookies = request.getCookies();
	        String historypro = null;
	        if(cookies!=null){
	            for(Cookie c:cookies){
	                if(c.getName().equals("historypro"+request.getParameter("userId"))){
	                    historypro = c.getValue();
	                    break;
	                }
	            }
	        }
	        if(cookies==null||historypro==null){
	            return id;
	        }
	        //historypro.contains(id);这种方法不对，原因：id数据类型为String,如果有一个id值为21，同样包含2
	        //String -> String[] ->  Collection :为了方便判断重复id
	        String[] ids = historypro.split(",");
	        Collection colls = Arrays.asList(ids); //<3,21>
	        // LinkedList 方便地操作（增删改元素）集合
	        // Collection -> LinkedList
	        LinkedList list = new LinkedList(colls);
	        //不超过3个
	        if(list.size()<3){
	            //id重复
	            if(list.contains(id)){
	                //去除重复id，把传入的id放最前面
	                list.remove(id);
	                list.addFirst(id);
	            }else{
	                //直接把传入的id放最前面
	                list.addFirst(id);
	            }
	        }else{
	            //等于3个
	            //id重复
	            if(list.contains(id)){
	                //去除重复id，把传入的id放最前面
	                list.remove(id);
	                list.addFirst(id);
	            }else{
	                //去最后的id，把传入的id放最前面
	                list.removeLast();
	                list.addFirst(id);
	            }
	        }
	        // LinedList -> String 
	        StringBuffer sb = new StringBuffer();
	        for (Object object : list) {
	            sb.append(object+",");
	        }
	        //去掉最后的逗号
	        String result = sb.toString();
	        result = result.substring(0, result.length()-1);
	        return result;
	    }
	
	

}
